import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '@/api/user.js'
import user from './modules/user.js'
import { saveToken, getToken } from '../utils/storage'

Vue.use(Vuex)

export default new Vuex.Store({
  // 公共数据
  state: {
    tokenInfo: getToken() || {}
  },
  // 定义mutation来修改数据
  mutations: {
    mSetTokenInfo (state, initTokenInfo) {
      state.tokenInfo = initTokenInfo
    }
  },
  actions: {
    async userLogin (context, userInfo) {
      try {
        const { data: { data } } = await login(userInfo)
        context.commit('mSetTokenInfo', data)
        saveToken(data)
      } catch (err) {
        // console.log(err)
        throw new Error(err)
      }
    }
  },
  modules: {
    user
  }
})
